package cn.com.ejiakanghu.service;

import cn.com.ejiakanghu.dto.PackageDto;
import cn.ejiakanghu.logistics.service.impl.LogisticBusiBaseServiceImpl;
import cn.ejiakanghu.logistics.task.OrderSelfTask;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.linlinjava.litemall.core.task.TaskService;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class PackageService {
    private Logger logger = LoggerFactory.getLogger(PackageService.class);
    @Autowired
    private LitemallOrderService orderService;
    @Autowired
    private LitemallOrderGoodsService orderGoodsService;
    @Autowired
    private AgedmallLgBaseInfoService agedmallLgBaseInfoService;
    @Autowired
    private LogisticsGoodsUtil logisticsGoodsUtil;
    @Autowired
    private AgedmallStoreService agedmallStoreService;
    @Autowired
    private AgedmallCloudHouseService agedmallCloudHouseService;
    @Autowired
    private AgedmallAnnouncerBaseInfoService agedmallAnnouncerBaseInfoService;
    @Autowired
    private LogisticBusiBaseServiceImpl logisticBusiBaseServiceImpl;
    @Resource
    private LitemallOrderGoodsMapper litemallOrderGoodsMapper;
    @Resource
    private AgedmallLgRfidGoodsCurStatMapper agedmallLgRfidGoodsCurStatMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private TaskService taskService;
    @Resource
    private AgedmallStoreGoodsMapper agedmallStoreGoodsMapper;
    @Resource
    private AgedmallHospitalWizardOrderMapper agedmallHospitalWizardOrderMapper;
    @Resource
    private AgedmallHospitalWizardOrderRecordMapper agedmallHospitalWizardOrderRecordMapper;
    @Resource
    private AgedmallHospitalSendSelfLocationMapper agedmallHospitalSendSelfLocationMapper;
    @Resource
    private LitemallUserMapper litemallUserMapper;
    @Resource
    private LitemallOrderItemMapper litemallOrderItemMapper;
    /**
     * 自提同一门店一个包裹，其余按云仓id、门店id分包裹
     * @param orderId
     */
    public void subpackage(Integer orderId) {
        logger.debug("订单{}开始分包", orderId);

        List<PackageDto> packageDtos = new ArrayList<>();

        LitemallOrder order = orderService.findById(orderId);
        List<LitemallOrderItem> subOrders = orderService.getOrderItemListByBigOrderCode(order.getUserId(), order.getOrderSn());
        for (LitemallOrderItem litemallOrder : subOrders) {
            List<LitemallOrderGoods> orderGoodsList = orderGoodsService.getOrderGoodsListByChildOrderCode(litemallOrder.getChildOrderCode());
            //判断是否是导医台自提，如果是，则不需要走物流配送
            if(orderGoodsList.get(0).getHospitalSelfLocationId()!=null&&orderGoodsList.get(0).getLocationHpType()==0){
                AgedmallHospitalSendSelfLocation location=agedmallHospitalSendSelfLocationMapper.selectByPrimaryKey(orderGoodsList.get(0).getHospitalSelfLocationId());

                String time=LogisticsGoodsUtil.getGoodsDeliveryTime(litemallOrder.getDeliverySn(),litemallOrder.getDeliveryChoose(),litemallOrder.getAddTime());

                LitemallUser litemallUser = litemallUserMapper.selectByPrimaryKey(litemallOrder.getUserId());
                // 增加导医台相关表 直接修改子订单为待收货
                AgedmallHospitalWizardOrder wizardOrder=new AgedmallHospitalWizardOrder();
                wizardOrder.setOrderItemId(litemallOrder.getId());
                wizardOrder.setOrderGoodsId(orderGoodsList.get(0).getId());
                wizardOrder.setNumber(orderGoodsList.get(0).getNumber().intValue());
                wizardOrder.setHospitalId(location.getHospitalId());
                wizardOrder.setHospitalSelfLocationId(orderGoodsList.get(0).getHospitalSelfLocationId());
                wizardOrder.setUserName(litemallUser.getNickname());
                wizardOrder.setPhone(litemallUser.getMobile());
                wizardOrder.setAppointmentTime(time);
                wizardOrder.setLockRfid(Integer.parseInt(orderGoodsList.get(0).getRfid()));
                wizardOrder.setState(0);
                wizardOrder.setAddTime(LocalDateTime.now());
                agedmallHospitalWizardOrderMapper.insertSelective(wizardOrder);

                AgedmallHospitalWizardOrderRecord wizardOrderRecord=new AgedmallHospitalWizardOrderRecord();
                wizardOrderRecord.setHospitalWizardOrderId(wizardOrder.getId());
                wizardOrderRecord.setChangeState(0);
                //0代表系统操作
                wizardOrderRecord.setOperatorUser(0L);
                wizardOrderRecord.setOperatorTime(LocalDateTime.now());
                agedmallHospitalWizardOrderRecordMapper.insertSelective(wizardOrderRecord);

                // 子订单为待收货
                litemallOrder.setOrderStatus(OrderUtil.STATUS_SHIP);
                litemallOrder.setShipTime(LocalDateTime.now());
                litemallOrderItemMapper.updateByPrimaryKeySelective(litemallOrder);
                continue;
            }
            // 是否自提
            if (null != litemallOrder.getExtractShop()) {
                Long selfTime = getSelfTime(litemallOrder);
                taskService.addTask(new OrderSelfTask(litemallOrder.getId(),selfTime));
                Integer selfId = litemallOrder.getStoreId();
                PackageDto packageDto = packageDtos.stream().filter(p -> p.getType() .equals(PackageDto.TYPE_SELF)  && p.getStoreId() .equals(selfId) ).findFirst().orElse(null);
                if (null == packageDto) {
                    packageDto = new PackageDto();
                    packageDto.setType(PackageDto.TYPE_SELF);
                    packageDto.setStoreId(selfId);
                    AgedmallStore store = agedmallStoreService.findStoreById(selfId);
                    packageDto.setStoreAddress(null == store ? "" : store.getAddressDetail());
                    // 配货 1按顺序 2全部 3手动
                    if (store.getDistributionMode() == 3) {
                        AgedmallAnnouncerBaseInfo announcerBaseInfo = agedmallAnnouncerBaseInfoService.queryByStoreId(selfId);
                        packageDto.setNoticeType(null == announcerBaseInfo ? PackageDto.NOTICETYPE_BROADCAST : PackageDto.NOTICETYPE_APPLET);
                    } else {
                        packageDto.setNoticeType(PackageDto.NOTICETYPE_WEIXIN);
                    }
                    packageDtos.add(packageDto);
                }
                List<Integer> orderGoodsIdList = orderGoodsList.stream().map(p -> p.getId()).collect(Collectors.toList());
                packageDto.getOrderGoodsIdList().addAll(orderGoodsIdList);
            } else {
                for (LitemallOrderGoods litemallOrderGoods : orderGoodsList) {
                    // 是否云仓
                    if (null != litemallOrderGoods.getCloudStockId()) {
                        Integer stockId = litemallOrderGoods.getCloudStockId();
                        PackageDto packageDto = packageDtos.stream().filter(p -> p.getType() .equals(PackageDto.TYPE_CLOUD)
                                && p.getStoreId() .equals(stockId) ).findFirst().orElse(null);
                        if (null == packageDto) {
                            packageDto = new PackageDto();
                            packageDto.setType(PackageDto.TYPE_CLOUD);
                            packageDto.setStoreId(stockId);
                            AgedmallCloudHouse house = agedmallCloudHouseService.getById(stockId);
                            packageDto.setStoreAddress(null == house ? "" : house.getAddressDetail());
                            AgedmallAnnouncerBaseInfo announcerBaseInfo = agedmallAnnouncerBaseInfoService.queryByStoreId(stockId);
                            packageDto.setNoticeType(null == announcerBaseInfo ? PackageDto.NOTICETYPE_BROADCAST : PackageDto.NOTICETYPE_APPLET);
                            packageDtos.add(packageDto);
                        }
                        packageDto.getOrderGoodsIdList().add(litemallOrderGoods.getId());
                    } else {
                        Integer stockId = litemallOrderGoods.getStoreId();
                        //配送 0-物流 1-自营
                        AgedmallStoreGoods storeGoods=agedmallStoreGoodsMapper.selectByPrimaryKey(litemallOrderGoods.getStoreGoodsId().longValue());
                        Integer disMode=storeGoods.getSameCitySendType();
                        PackageDto packageDto = packageDtos.stream().filter(p -> PackageDto.TYPE_STORE.equals(p.getType())
                                && stockId.equals(p.getStoreId())&&disMode.equals(p.getDistributionMode())).findFirst().orElse(null);
                        if (null == packageDto) {
                            packageDto = new PackageDto();
                            packageDto.setType(PackageDto.TYPE_STORE);
                            packageDto.setStoreId(stockId);
                            AgedmallStore store = agedmallStoreService.findStoreById(stockId);
                            packageDto.setStoreAddress(null == store ? "" : store.getAddressDetail());
                            // 配货 1按顺序 2全部 3手动
                            if (store.getDistributionMode() == 3) {
                                AgedmallAnnouncerBaseInfo announcerBaseInfo = agedmallAnnouncerBaseInfoService.queryByStoreId(stockId);
                                packageDto.setNoticeType(null == announcerBaseInfo ? PackageDto.NOTICETYPE_BROADCAST : PackageDto.NOTICETYPE_APPLET);
                            } else {
                                packageDto.setNoticeType(PackageDto.NOTICETYPE_WEIXIN);
                            }

                            packageDto.setDistributionMode(disMode);
                            packageDtos.add(packageDto);
                        }
                        packageDto.getOrderGoodsIdList().add(litemallOrderGoods.getId());
                    }
                }
            }
        }
        List<Integer> orderGoodsList=new ArrayList<>();
        // 加入包裹表
        for (PackageDto packageDto : packageDtos) {
            AgedmallLgBaseInfo agedmallLgBaseInfo = new AgedmallLgBaseInfo();
            agedmallLgBaseInfo.setOrderCode(order.getOrderSn()+"");
            agedmallLgBaseInfo.setLgType(PackageDto.TYPE_SELF.equals(packageDto.getType()) ? LgBaseInfoLgType.SELFPICKUP.getCode() : LgBaseInfoLgType.PURCHASING.getCode());
            agedmallLgBaseInfo.setLgContent(logisticsGoodsUtil.toJsonStringByOrderGoodsId(packageDto.getOrderGoodsIdList(),null));
            agedmallLgBaseInfo.setUserName(order.getConsignee());
            agedmallLgBaseInfo.setPhone(order.getMobile());
            agedmallLgBaseInfo.setAddresss(order.getAddress());
            agedmallLgBaseInfo.setWarehouseType(packageDto.getType().equals(PackageDto.TYPE_CLOUD)  ? 1 : 0);
            agedmallLgBaseInfo.setNoticeType(packageDto.getNoticeType());
            agedmallLgBaseInfo.setWarehouseAddress(packageDto.getStoreAddress());
            agedmallLgBaseInfo.setStoreId(packageDto.getStoreId());
            agedmallLgBaseInfo.setLgStat(LgBaseInfoStatConstant.BUY_UN_ALLOT);
            agedmallLgBaseInfo.setLgIsOver(0);
            agedmallLgBaseInfoService.add(agedmallLgBaseInfo);
            //自提准备自提码
            if(PackageDto.TYPE_SELF.equals(packageDto.getType())){
                stringRedisTemplate.opsForValue().set("self-"+agedmallLgBaseInfo.getId().toString()+"-code", RandomUtil.randomNumbers(6)
                ,24, TimeUnit.HOURS);
            }
            orderGoodsList.addAll(packageDto.getOrderGoodsIdList());
        }
        //rfid绑定订单id
        LitemallOrderGoodsExample orderGoodsExample=new LitemallOrderGoodsExample();
        orderGoodsExample.or().andIdIn(orderGoodsList);
        List<LitemallOrderGoods> litemallOrderGoods = litemallOrderGoodsMapper.selectByExample(orderGoodsExample);
        //软链
        List<String> chainRfid=new ArrayList<>();
        //衣柜锁
        List<String> cabinetRfid=new ArrayList<>();
        litemallOrderGoods.forEach( orderGoods ->{
            if(StrUtil.isNotBlank(orderGoods.getRfid())){
                String[] rfidString=orderGoods.getRfid().split(",");
                if(orderGoods.getStockType()==1){
                    for (int i = 0; i < rfidString.length; i++) {
                        chainRfid.add(rfidString[i]);
                    }
                }
                else if(orderGoods.getStockType()==2){
                    for (int i = 0; i < rfidString.length; i++) {
                        cabinetRfid.add(rfidString[i]);
                    }
                }
            }
        });
        if(!chainRfid.isEmpty()){
            AgedmallLgRfidGoodsCurStatExample chainExample=new AgedmallLgRfidGoodsCurStatExample();
            chainExample.or().andRfidIn(chainRfid).andTypeEqualTo(1);
            AgedmallLgRfidGoodsCurStat curStat=new AgedmallLgRfidGoodsCurStat();
            curStat.setLastOrderCode(order.getOrderSn());
            agedmallLgRfidGoodsCurStatMapper.updateByExampleSelective(curStat,chainExample);
        }
        if(!cabinetRfid.isEmpty()){
            AgedmallLgRfidGoodsCurStatExample cabinetExample=new AgedmallLgRfidGoodsCurStatExample();
            cabinetExample.or().andRfidIn(cabinetRfid).andTypeEqualTo(2);
            AgedmallLgRfidGoodsCurStat curStat=new AgedmallLgRfidGoodsCurStat();
            curStat.setLastOrderCode(order.getOrderSn());
            agedmallLgRfidGoodsCurStatMapper.updateByExampleSelective(curStat,cabinetExample);
        }


        //调用物流任务
        if(packageDtos.size()>0){
        logisticBusiBaseServiceImpl.userCreateOrderEvent(order.getOrderSn(),null, LogisticsMissionTypeEnum.ALLOT.getCode());
        }

    }

    //获取未自提自动取消世间
    public Long getSelfTime(LitemallOrderItem orderItem){
        LocalDateTime nowTime=LocalDateTime.now();
        LocalDateTime subTime=LocalDateTime.now();
        //默认为24小时候
        if(orderItem.getDeliverySn().equals(AgedmallShipDictConstant.SHIP_SN_SELF)){
            subTime=orderItem.getAddTime();
        }
        else if(orderItem.getDeliverySn().equals(AgedmallShipDictConstant.SHIP_SN_HOSPITAL)){
            JSONObject jsonObject= JSON.parseObject(orderItem.getDeliveryChoose());
            String type=(String) jsonObject.get("type");
            if(type.equals("subStoreSelf")||type.equals("subHospitalSelf")){
                JSONObject hosJSON=JSON.parseObject(orderItem.getDeliveryChoose());
                String date=(String) hosJSON.get("date")+" "+(String)hosJSON.get("endTime")+":00";
                subTime= cn.hutool.core.date.DateUtil.parseLocalDateTime(date);
            }
        }
        else{
            subTime=orderItem.getAddTime();
        }
        DateTime dateTime =cn.hutool.core.date.DateUtil.offsetDay(Date.from(subTime.atZone(ZoneId.systemDefault()).toInstant()), 1);
        Date nowDate = Date.from(nowTime.atZone(ZoneId.systemDefault()).toInstant());
        Long betweenSecond=DateUtil.between(dateTime.toJdkDate(),nowDate,DateUnit.MS);
        return betweenSecond;
    }
}
